import { getUserInfo, login, getUserInDetailfoById } from '@/api/user'

const state = {
  token: localStorage.getItem('token') || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    localStorage.setItem('token', data)
    state.token = data
    // console.log(state.token)
  },
  // 登出页面删除token 和本地存储
  removeToken(state) {
    state.token = ''
    localStorage.removeItem('token')
  },
  setUserInfo(state, data) {
    state.userInfo = { ...data }
    // console.log(state.userInfo)
  },
  removeInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  login: async function(store, data) {
    // console.log('Vuex actions登录请求')
    const res = await login(data)
    store.commit('setToken', res)
    // console.log('Vuex actions登录请求', res)
  },
  async getUserInfo(store) {
    const res = await getUserInfo()
    const detail = await getUserInDetailfoById(res.userId)
    // 此处的getUserInfo是请求数据的
    store.commit('setUserInfo', { ...res, ...detail })
  },
  async logout(store) {
    store.commit('removeToken')
    store.commit('removeInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
